package com.five.matebook.activity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.five.matebook.R;
import com.five.matebook.activity.columeedit.CustomValueManager;
import com.five.matebook.activity.db.IncomeRecordTable;
import com.five.matebook.activity.db.OneQueryData;
import com.five.matebook.activity.db.QueryFilter;
import com.five.matebook.activity.income.IncomeColume;
import com.five.matebook.activity.income.IncomeLsitFragment;
import com.five.matebook.activity.stat.IncomeStatFragment;
import com.five.matebook.activity.stat.OutcomeStatFragment;
import com.five.matebook.utils.DateAlias;
import com.five.matebook.utils.DateUtils;
import com.five.matebook.utils.StringTreeParser;

import java.util.Date;
import java.util.List;

public class QueryActivityIncome extends BaseRecordActivity {
    private static final String TAG = QueryActivityIncome.class.getSimpleName();

    private StringTreeParser mUsageListParser;

    private Spinner mSpinnerUsageMain;
    private Spinner mSpinnerUsageSecond;
    private EditText mEditMoneyBegin;
    private EditText mEditMoneyEnd;
    private Spinner mSpinnerSpentRole;
    private EditText mEditRemarks;

    private TextView mTxtBeginTime;
    private TextView mTxtEndTime;
    private Spinner mSpinnerTimeAlias;

    private List<StringTreeParser.StringItem> mainUsageList;

    private TextView mQueryTableInterview;
    private ScrollView mScrollView;
    private TextView mTxtNowQueryCondition;

    private Button mBtnShowList;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_income);

        mQueryTableInterview = findViewById(R.id.txt_query_tables);
        mTxtNowQueryCondition = findViewById(R.id.txt_now_query_conditon);
        mBtnShowList = findViewById(R.id.btn_show_list);
        mScrollView = findViewById(R.id.scrollView);
        {
            final View parent = ((View)mQueryTableInterview.getParent());
            parent.setSelected(true);
            parent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean selectd = parent.isSelected();
                    if (selectd) {
//                        mScrollView.setVisibility(View.GONE);
//                        mTxtNowQueryCondition.setVisibility(View.VISIBLE);
                        return;
                    } else {
                        mScrollView.setVisibility(View.VISIBLE);
                        mTxtNowQueryCondition.setVisibility(View.GONE);
                    }
                    parent.setSelected(!selectd);
                }
            });
        }

        {
            this.mSpinnerUsageMain = findViewById(R.id.spinner_usage_main);
            this.mSpinnerUsageSecond = findViewById(R.id.spinner_usage_sencond);
            this.mTxtBeginTime = findViewById(R.id.txt_begintime);
            this.mTxtEndTime = findViewById(R.id.txt_endtime);
            this.mSpinnerTimeAlias = findViewById(R.id.spinner_time_alias);
            this.mEditMoneyBegin = findViewById(R.id.edit_money_begin);
            this.mEditMoneyEnd = findViewById(R.id.edit_money_end);
            this.mSpinnerSpentRole = findViewById(R.id.spent_role);
            this.mEditRemarks = findViewById(R.id.edit_remark);
        }

        {
            /*
             ** 初始化： 用途下拉框
             */
            mUsageListParser = getStringTreeParser(CustomValueManager.FILED_USAGE_INCOME, R.array.usageListMain, 2);
            mainUsageList = mUsageListParser.getArray(1);

            this.mSpinnerUsageMain.setAdapter(generateSpinnerAdapter(mainUsageList));
            this.mSpinnerUsageMain.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    parent.getAdapter().getItem(position);
                    if (position == 0) {
                        // nothing selected
                        mSpinnerUsageSecond.setAdapter(null);
                    } else {
                        mSpinnerUsageSecond.setAdapter(generateSpinnerAdapter(mUsageListParser.getArray(mainUsageList.get(position))));
                        mSpinnerUsageSecond.performClick();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        }
        {
            /*
             ** 初始化： 日期
             */

            this.mTxtBeginTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Calendar calendar = Calendar.getInstance();
                    new DatePickerDialog(QueryActivityIncome.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                            Date d = DateUtils.string2Date(year, month, dayOfMonth, 0, 0, 0);
                            setBeginTime(d.getTime());
                            mSpinnerTimeAlias.setSelection(0);
                        }
                    }, calendar.get(Calendar.YEAR), // 年份
                            calendar.get(Calendar.MONTH), // 月份
                            calendar.get(Calendar.DAY_OF_MONTH)).show();
                }
            });

            this.mTxtEndTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Calendar calendar = Calendar.getInstance();
                    new DatePickerDialog(QueryActivityIncome.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                            Date d = DateUtils.string2Date(year, month, dayOfMonth, 23, 59, 59);
                            setEndTime(d.getTime());
                            mSpinnerTimeAlias.setSelection(0);
                        }
                    }, calendar.get(Calendar.YEAR), // 年份
                            calendar.get(Calendar.MONTH), // 月份
                            calendar.get(Calendar.DAY_OF_MONTH)).show();

                }
            });

            List<String> timeAlisList = DateUtils.getAliasList();
            timeAlisList.add(0, "");
            mSpinnerTimeAlias.setAdapter(generateSpinnerAdapter(timeAlisList));
            mSpinnerTimeAlias.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position != 0) {
                        DateAlias.DateRange range = DateUtils.getDateRangeByAlias(mSpinnerTimeAlias.getSelectedItem().toString());
                        setBeginTime(range.begin);
                        setEndTime(range.end);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            setSpinnerText(mSpinnerTimeAlias, "本月", false);
        }

        {
            // 对象
            StringTreeParser roleTreeParser = getStringTreeParser(CustomValueManager.FILED_ROLE_INCOME, R.array.spentRole, 1);
            mSpinnerSpentRole.setAdapter(generateSpinnerAdapter(roleTreeParser.getArray(1)));
        }
    }

    private void setBeginTime(long begin) {
        setTime2TextView(mTxtBeginTime, begin, true);
    }
    private void setEndTime(long end) {
        setTime2TextView(mTxtEndTime, end, true);
    }

    private void doToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    private List<OneQueryData> queryDataList;

    public void onClick_doQuery(View v) {
        QueryFilter.Builder builder = new QueryFilter.Builder();
        StringBuffer sb = new StringBuffer();

        // 金额限制
        float beginMoney = getTextviewValue(mEditMoneyBegin, 0);
        float endMoney = getTextviewValue(mEditMoneyEnd, 0);
        if (endMoney < beginMoney) {
            doToast("截止金额不能小于起始金额");
            return;
        }
        if (beginMoney != 0 || endMoney != 0) {
            builder.addFloatRange(IncomeColume.SPENT_MONEY, beginMoney, endMoney);
            sb.append(String.format("金额: %.2f ~ %.2f\n", beginMoney, endMoney));
        }

        // 用途限制
        boolean hasUsage = false;
        String mainUsage = getSpinnerValue(mSpinnerUsageMain);
        String secondUsage = getSpinnerValue(mSpinnerUsageSecond);
        if (!TextUtils.isEmpty(mainUsage)) {
            builder.addStringMatch(IncomeColume.SPENT_USAGE, mainUsage, true);
            sb.append(String.format("用途: %s", mainUsage));
            hasUsage = true;
        }
        if (!TextUtils.isEmpty(secondUsage)) {
            builder.addStringMatch(IncomeColume.SPENT_SENCOND_USAGE, secondUsage, true);
            sb.append(String.format(" - %s", secondUsage));
        }
        if (hasUsage)   sb.append("\n");

        // 时间
        long begin = getTimeFromTextView(mTxtBeginTime);
        long end = getTimeFromTextView(mTxtEndTime);

        if (end < begin) {
            doToast("结束时间不能小于开始时间");
            return;
        }
        sb.append(String.format("时间范围: %s ~ %s\n", DateUtils.toString(begin, true), DateUtils.toString(end, true)));
        builder.addLongRange(IncomeColume.HAPPEND_TIME, begin, end);

        // 对象
        String spentRole = getSpinnerValue(mSpinnerSpentRole);
        if (!TextUtils.isEmpty(spentRole)) {
            builder.addStringMatch(IncomeColume.INCOME_ROLE, spentRole, true);
            sb.append(String.format("对象: %s\n", spentRole));
        }

        // 备注
        String remarks = String.valueOf(mEditRemarks.getText());
        if (!TextUtils.isEmpty(remarks)) {
            builder.addStringMatch(IncomeColume.SPENT_REMARKS, remarks, false);
            sb.append(String.format("备注: %s", remarks));
        }

        builder.setOrderBy(IncomeColume.HAPPEND_TIME, true);
        QueryFilter filter = builder.build();

        {
            mTxtNowQueryCondition.setText(sb.toString());
            mTxtNowQueryCondition.setVisibility(View.VISIBLE);
            View parent = (View) mQueryTableInterview.getParent();
            parent.setSelected(false);
            mScrollView.setVisibility(View.GONE);
        }

        queryDataList = IncomeRecordTable.getInstance(this).query(filter);
        showFragment(false, false);
    }

    private void showFragment(boolean isListFrag, boolean add2BackStack) {
        Fragment fragment = null;

        if (isListFrag) {
            IncomeLsitFragment f = new IncomeLsitFragment(queryDataList);
            fragment = f;
            mBtnShowList.setVisibility(View.GONE);
        } else {
            IncomeStatFragment f = new IncomeStatFragment(queryDataList);
            fragment = f;
            mBtnShowList.setVisibility(View.VISIBLE);
        }
        // 获取 FragmentManager
        FragmentManager fragmentManager = getSupportFragmentManager();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        fragmentTransaction.replace(R.id.fragment_container_view, fragment);

        if (add2BackStack) {
            fragmentTransaction.addToBackStack(null);
            fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
                @Override
                public void onBackStackChanged() {
                    if (fragmentManager.getBackStackEntryCount() == 0) {
                        mBtnShowList.setVisibility(View.VISIBLE);
                    }
                }
            });
        }

        fragmentTransaction.commit();
    }

    @Override
    protected void updateChildUi() {

    }

    public void onClick_showRecordList(View v) {
//        showFragment(true, true);
        new InrecordViewDialog(queryDataList).show(getSupportFragmentManager(), "");
    }
}
